package cn.tlb.upload;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.tlb.xutilsdownload.R;

public class FormSubmitActivity extends AppCompatActivity {
    private static final String PIC_DIR = Environment.getExternalStorageDirectory() + "/Pictures/Screenshots";
    private static final String TAG = FormSubmitActivity.class.getSimpleName();
    @Bind(R.id.listView) ListView listView;

    private Form form;
    ArrayList<Input> inputs;
    private Button add;

    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form_submit);
        ButterKnife.bind(this);

        form = new Form("http://192.168.47.146:8080/http/servlet/FileUploadServlet", "POST");
        inputs = form.inputs;
        add = new Button(this);
        listView.addFooterView(add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inputs.add(new Input());
            }
        });

        testService();
    }

    public void testService(){
        Form form = new Form("http://192.168.50.211:5151/service/user/resource/create/version/1.5", "POST");

        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("type", "1");
        map.put("title", "upload_test");
        map.put("cateId", "1");
        map.put("description", "map description. description description description...");
        map.put("game_versions", "0.12");

        for(Map.Entry<String, String> entry : map.entrySet()){
            form.inputs.add(Input.newTextInput(entry.getKey(), entry.getValue()));
        }

        File file = new File(PIC_DIR+"/"+"map_ex.zip");
        form.inputs.add(Input.newFileInput("zip", file.getAbsolutePath()));


        new FormUtil().uploadMultipartForm(form, new MyListener());
    }

    private static class MyListener implements FormUtil.OnSubmitListener{

        @Override
        public void onStart() {
            Log.i(TAG, "onStart");
        }

        @Override
        public void onError(Throwable th) {
            Log.i(TAG, "onError--->"+th);
        }

        @Override
        public void onUploading(String absFilePath, long totalSize, long uploadSize, int progress) {

        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onSuccess(String result) {
            Log.i(TAG, "onSuccess--->"+result);
        }

        @Override
        public void onFailed(int responseCode) {

        }

        @Override
        public void onFinish() {

        }
    }

    @OnClick(R.id.submit) void submit(){
        new FormUtil().uploadMultipartForm(form, new FormUtil.OnSubmitListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onError(Throwable th) {
                Toast.makeText(FormSubmitActivity.this, th.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onUploading(String path, long totalSize, long uploadSize, int progress) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onSuccess(String result) {
                Toast.makeText(FormSubmitActivity.this, result, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(int responseCode) {
                Toast.makeText(FormSubmitActivity.this, "responseCode;"+responseCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {

            }
        });
    }

    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return inputs.size();
        }

        @Override
        public Object getItem(int position) {
            return inputs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final Input input = inputs.get(position);
            if(convertView == null){
                convertView = getLayoutInflater().inflate(R.layout.form_item, null);
            }

            ((TextView)ViewHolder.getView(convertView, R.id.order)).setText((position + 1) + "");
            EditText name = (EditText) ViewHolder.getView(convertView, R.id.name);
            name.addTextChangedListener(new DefaultTextWatcher(){
                @Override
                public void afterTextChanged(Editable s) {
                    input.name = s.toString();
                    notifyDataSetChanged();
                }
            });
            name.setText(input.name);
            EditText value = (EditText) ViewHolder.getView(convertView, R.id.value);
            value.addTextChangedListener(new DefaultTextWatcher(){
                @Override
                public void afterTextChanged(Editable s) {
                    input.value = s.toString();
                    notifyDataSetChanged();
                }
            });

            Spinner spinner = (Spinner) ViewHolder.getView(convertView, R.id.spinner);
            spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    input.type = position == 0 ? Input.Type.TEXT : Input.Type.FILE;
                }
            });
            switch(input.type){
                case TEXT:
                    value.setText(input.value);
                    break;
                case FILE:
                    value.setText(input.filename);
                    break;
            }


            return convertView;
        }



    }
    class DefaultTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    static class ViewHolder{
        public static View getView(View parent, int id){
            SparseArray<View> viewSparseArray = (SparseArray<View>) parent.getTag();
            if(viewSparseArray == null){
                viewSparseArray = new SparseArray<>();
                parent.setTag(viewSparseArray);
            }

            View child = viewSparseArray.get(id);
            if(child == null){
                child = parent.findViewById(id);
                viewSparseArray.put(id, child);
            }
            return child;
        }
    }
}
